package com.xjd.edu.common.admin.dict;


import cn.hutool.json.JSONArray;
import com.xjd.edu.common.admin.core.constant.CacheConstants;
import com.xjd.edu.common.admin.domain.SysDictData;
import com.xjd.edu.toolkit.cache.GameRedisTemplate;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * 字典服务本地缓存实现
 *
 * @author wangyu
 * @date 2024/09/18 10:28
 */
@Slf4j
public class LocalDictService implements DictService {

    private GameRedisTemplate gameRedisTemplate;


    public LocalDictService(GameRedisTemplate gameRedisTemplate) {
        this.gameRedisTemplate = gameRedisTemplate;
    }

    /**
     * 设置字典缓存
     *
     * @param key       参数键
     * @param dictDatas 字典数据列表
     */
    public void setDictCache(String key, List<SysDictData> dictDatas) {
        //SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas);
        //todo redis
        gameRedisTemplate.set(getCacheKey(key), dictDatas, Duration.ofDays(365));
    }

    /**
     * 获取字典缓存
     *
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public List<SysDictData> getDictCache(String key) {
        //val objects1 = gameRedisTemplate.get(getCacheKey(key)).map(JSONArray::new);
        Optional<JSONArray> arrayCache = gameRedisTemplate.get(getCacheKey(key)).map(JSONArray::new);
        return arrayCache.map(objects -> objects.toList(SysDictData.class)).orElse(null);
    }

    /**
     * 删除指定字典缓存
     *
     * @param key 字典键
     */
    public void removeDictCache(String key) {
        //SpringUtils.getBean(RedisService.class).deleteObject(getCacheKey(key));
        //todo redis
        gameRedisTemplate.del(getCacheKey(key));
    }

    /**
     * 清空字典缓存
     */
    public void clearDictCache() {
        Collection<String> keys = gameRedisTemplate.keys(CacheConstants.SYS_DICT_KEY + "*");
        for (String key : keys) {
            gameRedisTemplate.del(key);
        }
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public String getCacheKey(String configKey) {
        return CacheConstants.SYS_DICT_KEY + configKey;
    }
}
